<?php 
namespace xfyzf\user\controller;
use xfyzf\api\controller\Examine;
use xfyzf\api\controller\XFCookie;
use xfyzf\api\controller\Pay_Money_Api;
use xfyzf\api\controller\QQ_Protocol;
use xfyzf\api\controller\WXMac_Protocol;
use xfyzf\api\controller\WXUOS_Protocol;
use lib\XFCaptcha;
class Ajax{
    public function __construct($url = ''){
        $this->Captcha = new XFCaptcha(CaptchaCode);
    }
    //极验
    public function Captcha(){
        global $conf;
        $GtSdk = new \lib\GeetestLib($conf['captcha_id'], $conf['captcha_key']);
        $t = input("get")['t'];
        $data = array(
    		'user_id' => $t, # 网站用户id
    		'client_type' => "web", # web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
    		'ip_address' => http_ip() # 请在此处传输用户请求验证时所携带的IP
    	);
    	$status = $GtSdk->pre_process($data, 1);
    	$_SESSION['gtserver'] = $status;
    	$_SESSION['user_id'] = isset($t)?$t:'public';
    	exit($GtSdk->get_response_str());
    }
    //登录 
    public function Login(){
        global $conf, $islogin_user, $password_hash;
        
        // 判断用户是否已登录
        if ($islogin_user == '1') {
            exitjson(-1,'您已登陆！');
        }
        
        $postdata = input("post");
        $sendto = $postdata['sendto'];
        $GtSdk = new \lib\GeetestLib($conf['captcha_id'], $conf['captcha_key']);
        $data = array(
            'user_id' => $_SESSION['user_id'], # 网站用户id
            'client_type' => "web", # web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            'ip_address' => http_ip() # 请在此处传输用户请求验证时所携带的IP
        );
        
        if ($_SESSION['gtserver'] == 1){
            $result = $GtSdk->success_validate($postdata['geetest_challenge'], $postdata['geetest_validate'], $postdata['geetest_seccode'], $data);
            if (!$result) {
                exitjson(-1,'验证失败，请重新验证');
            }
        } else {
            if (!$GtSdk->fail_validate($postdata['geetest_challenge'],$postdata['geetest_validate'],$postdata['geetest_seccode'])) {
                exitjson(-1,'验证失败，请重新验证');
            }
        }
        
        $user = $postdata['pid'];
        $pwd = $postdata['key'];
        
        // 检查账号密码是否为空
        if (empty($user) || empty($pwd)) {
            exitjson(-1,'账号密码不可为空！');
        }
        
        // 查询用户信息
        $sql = "SELECT * FROM pay_user WHERE user=:user LIMIT 1";
        $params = ['user' => $user];
        $userrow = safeSqlQuery($sql, $params)['result'][0];
        
        // 检查用户是否存在
        if (!$userrow) {
            exitjson(-1,'登录失败！账号或密码错误');
        }
        
        $pass = md5(md5($pwd));
        
        // 检查密码是否正确
        if ($pass != $userrow['pass']) {
            exitjson(-1,'登录失败！账号或密码错误');
        }
        
        // 检查账号状态是否正常
        if ($userrow['zt'] != 1) {
            exitjson(-1,"登录失败 原因：账号被封禁，详情请联系站长QQ：" . $conf['qq']);
        }
        
        $pid = $userrow['pid'];
        $key = $userrow['key'];
        $session = md5($pid . $key . $password_hash);
        $expiretime = time() + 604800;
        $token = aes256auth("{$user}\t{$session}\t{$expiretime}","user_token",'ENCODE');
        setcookie("user_token", $token, $expiretime);
        createLog($pid, '登录用户中心成功', http_ip());
        exitjson(1, "登录成功");  
    }
    public function Login1(){
        global $conf, $islogin_user, $password_hash;
         // 判断用户是否已登录
        if ($islogin_user == '1') exitjson(-1,'您已登陆！');
        $postdata = input("post");
        $user = $postdata['pid'];
        $pwd = $postdata['key'];
        if(!$this->Captcha->XYcaptcha($postdata['code_input']))exitjson(-1,'验证码为空或错误！');
        // 检查账号密码是否为空
        if (empty($user) || empty($pwd)) {
            exitjson(-1,'账号密码不可为空！');
        }
        
        // 查询用户信息
        $sql = "SELECT * FROM pay_user WHERE user=:user LIMIT 1";
        $params = ['user' => $user];
        $userrow = safeSqlQuery($sql, $params)['result'][0];
        
        // 检查用户是否存在
        if (!$userrow) {
            exitjson(-1,'登录失败！账号或密码错误');
        }
        
        $pass = md5(md5($pwd));
        
        // 检查密码是否正确
        if ($pass != $userrow['pass']) {
            exitjson(-1,'登录失败！账号或密码错误');
        }
        
        // 检查账号状态是否正常
        if ($userrow['zt'] != 1) {
            exitjson(-1,"登录失败 原因：账号被封禁，详情请联系站长QQ：" . $conf['qq']);
        }
        
        $pid = $userrow['pid'];
        $key = $userrow['key'];
        $session = md5($pid . $key . $password_hash);
        $expiretime = time() + 604800;
        $token = aes256auth("{$user}\t{$session}\t{$expiretime}","user_token",'ENCODE');
        setcookie("user_token", $token, $expiretime);
        createLog($pid, '登录用户中心成功', http_ip());
        exitjson(1, "登录成功");  
    }
    //注册验证码
    public function Sendcode(){
        global $islogin_user,$conf;
         if($islogin_user == 1)exitjson(-1,'您已登陆！');
        // 获取 POST 数据
        $postdata = input("post");
        $email = $postdata['email'];
        $user = $postdata['user'];
        $qq = $postdata['qq'];
        $phone = $postdata['phone'];
       if(!$this->Captcha->XYcaptcha($postdata['code_input']))exitjson(-1,'验证码为空或错误！');
        if ($conf['reg_open']!= 1) exitjson(-1,'管理员未开放注册！');
        
        // 检查必填字段是否为空
        if (empty($email) || empty($user) || empty($qq)) {
            exitjson(-1, '邮箱、用户名、QQ不可为空！');
        }
    
        // 如果验证方式是手机号，检查手机号是否为空
        if ($conf['verifytype'] == 'phone' && empty($phone)) {
            exitjson(-1, '手机号不可为空！');
        }
        // 执行用户数据的检查
        $to = Examine::UserRegexamine($postdata);
        
        // 获取最近一次发送验证码的记录
        $sql = "SELECT * FROM pay_regcode WHERE `to`=:to ORDER BY id DESC LIMIT 1";
        $params = ['to' => $to];
        $row = safeSqlQuery($sql, $params)['result'][0] ?? '';
    
        // 两次发送间隔必须大于60秒
        if ($row['time'] > time() - 60) {
            exitjson(-1, "两次发送短信之间需要相隔60秒！");
        }
    
        // 获取最近24小时内的发送次数
        $sql = "SELECT COUNT(*) FROM pay_regcode WHERE `to`=:to AND `time`>:time";
        $params = ['to' => $to, 'time' => time() - 3600 * 24];
        $count = safeSqlQuery($sql, $params)['count']??'0';
        if ($count > 6) {
            exitjson(-1, "发送次数过多，请更换收信方式！");
        }
    
        // 获取最近24小时内当前 IP 的发送次数
        $sql = "SELECT COUNT(*) FROM pay_regcode WHERE `ip`=:ip AND `time`>:time";
        $params = ['ip' => http_ip(), 'time' => time() - 3600 * 24];
        $count = safeSqlQuery($sql, $params)['count']??'0';
        if ($count > 10) {
            exitjson(-1, "你今天发送次数过多，已被禁止注册");
        }
    
        // 生成随机验证码
        $code = rand(111111, 999999);
    
        // 发送验证码，根据配置不同选择发送方式
        if ($conf['verifytype'] == 'phone') {
            // 发送短信验证码
            $json = json_decode(send_sms($to, $code, 'reg'), true);
            $sms_auth = ($json['code'] == 200);
        } else {
            // 发送邮件验证码
            $sub = $conf['sitename'] . ' - 验证码获取';
            $msg = '您的注册验证码是：' . $code;
            $result = send_mail($email, $sub, $msg);
            $sms_auth = $result;
        }
    
        // 根据发送结果处理
        if ($sms_auth) {
            // 验证码发送成功，写入数据库
            $sql = "INSERT INTO `pay_regcode` (`type`, `code`, `to`, `time`, `ip`, `status`) VALUES ('0', :code, :to, :time, :ip, '0')";
            $params = ['code' => $code, 'to' => $to, 'time' => time(), 'ip' => http_ip()];
            if (safeSqlQuery($sql, $params, 'insert')) {
                $_SESSION['send_mail'] = time();
                exitjson(200, "验证码发送成功");
            } else {
                exitjson(-1, "验证码写入失败");
            }
        } else {
            // 验证码发送失败
            exitjson(-1, "验证码发送失败");
        }
    }
     //注册验证码
    public function Sendcode1(){
        global $islogin_user,$conf;
        // 获取 POST 数据
       $postdata = input("post");
        $sendto = $postdata['sendto'];
        $GtSdk = new \lib\GeetestLib($conf['captcha_id'], $conf['captcha_key']);
        $data = array(
            'user_id' => $_SESSION['user_id'], # 网站用户id
            'client_type' => "web", # web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            'ip_address' => http_ip() # 请在此处传输用户请求验证时所携带的IP
        );
        
        if ($_SESSION['gtserver'] == 1){
            $result = $GtSdk->success_validate($postdata['geetest_challenge'], $postdata['geetest_validate'], $postdata['geetest_seccode'], $data);
            if (!$result) {
                exitjson(-1,'验证失败，请重新验证');
            }
        } else {
            if (!$GtSdk->fail_validate($postdata['geetest_challenge'],$postdata['geetest_validate'],$postdata['geetest_seccode'])) {
                exitjson(-1,'验证失败，请重新验证');
            }
        }
        $email = $postdata['email'];
        $user = $postdata['user'];
        $qq = $postdata['qq'];
        $phone = $postdata['phone'];
        if($islogin_user == 1)exitjson(-1,'您已登陆！');
        if ($conf['reg_open']!= 1) exitjson(-1,'管理员未开放注册！');
        // 检查必填字段是否为空
        if (empty($email) || empty($user) || empty($qq)) {
            exitjson(-1, '邮箱、用户名、QQ不可为空！');
        }
    
        // 如果验证方式是手机号，检查手机号是否为空
        if ($conf['verifytype'] == 'phone' && empty($phone)) {
            exitjson(-1, '手机号不可为空！');
        }
        // 执行用户数据的检查
        $to = Examine::UserRegexamine($postdata);
        
        // 获取最近一次发送验证码的记录
        $sql = "SELECT * FROM pay_regcode WHERE `to`=:to ORDER BY id DESC LIMIT 1";
        $params = ['to' => $to];
        $row = safeSqlQuery($sql, $params)['result'][0] ?? '';
    
        // 两次发送间隔必须大于60秒
        if ($row['time'] > time() - 60) {
            exitjson(-1, "两次发送短信之间需要相隔60秒！");
        }
    
        // 获取最近24小时内的发送次数
        $sql = "SELECT COUNT(*) FROM pay_regcode WHERE `to`=:to AND `time`>:time";
        $params = ['to' => $to, 'time' => time() - 3600 * 24];
        $count = safeSqlQuery($sql, $params)['count']??'0';
        if ($count > 6) {
            exitjson(-1, "发送次数过多，请更换收信方式！");
        }
    
        // 获取最近24小时内当前 IP 的发送次数
        $sql = "SELECT COUNT(*) FROM pay_regcode WHERE `ip`=:ip AND `time`>:time";
        $params = ['ip' => http_ip(), 'time' => time() - 3600 * 24];
        $count = safeSqlQuery($sql, $params)['count']??'0';
        if ($count > 10) {
            exitjson(-1, "你今天发送次数过多，已被禁止注册");
        }
    
        // 生成随机验证码
        $code = rand(111111, 999999);
    
        // 发送验证码，根据配置不同选择发送方式
        if ($conf['verifytype'] == 'phone') {
            // 发送短信验证码
            $json = json_decode(send_sms($to, $code, 'reg'), true);
            $sms_auth = ($json['code'] == 200);
        } else {
            // 发送邮件验证码
            $sub = $conf['sitename'] . ' - 验证码获取';
            $msg = '您的注册验证码是：' . $code;
            $result = send_mail($email, $sub, $msg);
            $sms_auth = $result;
        }
    
        // 根据发送结果处理
        if ($sms_auth) {
            // 验证码发送成功，写入数据库
            $sql = "INSERT INTO `pay_regcode` (`type`, `code`, `to`, `time`, `ip`, `status`) VALUES ('0', :code, :to, :time, :ip, '0')";
            $params = ['code' => $code, 'to' => $to, 'time' => time(), 'ip' => http_ip()];
            if (safeSqlQuery($sql, $params, 'insert')) {
                $_SESSION['send_mail'] = time();
                exitjson(200, "验证码发送成功");
            } else {
                exitjson(-1, "验证码写入失败");
            }
        } else {
            // 验证码发送失败
            exitjson(-1, "验证码发送失败");
        }
    }
    
    //注册
    public function Reg(){
        global $conf,$httphost,$date,$islogin_user;
        $postdata   = input("post");
        $user       = $postdata['user'];
        $pass       = $postdata['pass'];
        $qq         = $postdata['qq'];
        $email      = $postdata['email'];
        $code       = $postdata['code'];
        $phone      = $postdata['phone'];
        if($islogin_user == 1)exitjson(-1,'您已登陆！');
        if ($conf['reg_open']!= 1) exitjson(-1,'管理员未开放注册！');
        // 检查必填字段是否为空
        if (empty($email) || empty($user) || empty($qq)) {
            exitjson(-1, '邮箱、用户名、QQ不可为空！');
        }
    
        // 如果验证方式是手机号，检查手机号是否为空
        if ($conf['verifytype'] == 'phone' && empty($phone)) {
            exitjson(-1, '手机号不可为空！');
        }
        $to = Examine::UserRegexamine($postdata);
        $pass = md5(md5($pass));
        $sql = "SELECT * FROM pay_regcode WHERE `to`=:to AND `code`=:code order by id desc LIMIT 1"; 
        $params = ['to' => $to, 'code' => $code];
        $result = safeSqlQuery($sql, $params)['result'][0]??'';
       
        if(!$result)exitjson(-1,'验证码不正确！');
        if($result['time']<time()-300 || $result['status']==1)exitjson(-1,'验证码已失效，请重新获取!');
        if($conf['reg_pay']==1){
            $sql = "select * from `pay_user` where `pid`='{$conf['zero_pid']}' limit 1";
            $gid = executeSQLQuery($sql);
            if(!$gid)exitjson(-1,'注册收款商户ID不存在!');
            $return_url = $httphost.'/User/login';
            $trade_no=date("YmdHis").rand(11111,99999);
            $data = '|'.$user.'|'.$pass.'|'.$email.'|'.$qq.'|'.$phone;
            $sql = "UPDATE `pay_regcode` SET `trade_no`='{$trade_no}',`data`='{$data}' WHERE `id`='{$result['id']}'";
            if(executeSQLQuery($sql,'update')){
                $wxpay = array("id"=>1,"name"=>"wxpay","showname"=>"微信");
    			$qqpay = array("id"=>2,"name"=>"qqpay","showname"=>"QQ钱包");
    			$alipay = array("id"=>3,"name"=>"alipay","showname"=>"支付宝");
    			$usdtpay = array("id"=>4,"name"=>"usdt","showname"=>"Usdt-TRC20");
                $res = array(
                    "trade_no"=>$trade_no,
                    "need"=>$conf['reg_pay_price'],
                    "paytype"=>array("1"=>$wxpay,"2"=>$qqpay,"3"=>$alipay,"4"=>$usdtpay)
                    );
                exitjson(1,'订单创建成功 请支付'.$conf['reg_pay_price'].'元 完成注册',$res);
            }else{
                exitjson(-1,'订单创建失败！');
            }
        }else{
            $emailauth = 0;
            if($conf['verifytype'] == 'email')$emailauth = 1;
            $pid='1'.mt_rand(10000000,99999999);
            $key = md5(random(11));
            $money = $conf['reg_money']??'0.00';
            $vip = null;
            if($conf['user_vip']>0){
                $vip= date("Y-m-d H:i:s", strtotime("+{$conf['user_vip']}days")); //计算会员到期时间
            }
            $sql = "INSERT INTO `pay_user` (`user`,`pass`,`pid`,`key`,`qq`,`email`,`phone`,`money`,`addtime`,`emailauth`) VALUES ('{$user}','{$pass}','{$pid}','{$key}','{$qq}','{$email}','{$phone}','{$money}','{$date}','{$emailauth}')";
            if(executeSQLQuery($sql,'insert')){
                if($vip){
                    $sql = "update `pay_user` set `wxpay_free_vip_time`='{$vip}',`qqpay_free_vip_time`='{$vip}',`alipay_free_vip_time`='{$vip}' where pid='{$pid}'";
                    executeSQLQuery($sql,'update');
                }
                $sql ="update `pay_regcode` set `status` ='1' where `id`='{$result['id']}'";
                executeSQLQuery($sql,'update');
                send_regsucc($user,$postdata['pass'],$email,true);
                send_regsucc($user,$postdata['pass'],$phone);
                createLog($pid,'申请商户成功',http_ip());
                exitjson(200,'申请商户成功！');
            }
        }
        exitjson(-1,'申请商户失败！');
    }
    //重置key
    public function Reset_key(){
        global $islogin_user,$userrow;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        if(isset($_SESSION['Reset_Token']) && $_SESSION['Reset_Token']>time()-3600)exitjson(-1,'请勿频繁修改秘钥!');
        $key = md5(random(11).$userrow['qq']);
        $sql = "update `pay_user` set `key` ='{$key}' where `pid`='{$userrow['pid']}'";
        if(executeSQLQuery($sql,'update')){
          createLog($userrow['pid'],'重置key密钥成功',http_ip());  
          $_SESSION['Reset_Token']=time();
          exitjson(200,'重置成功！');
        }
        exitjson(-1,'重置失败！');
    }
    //二级密码 效验
    public function Pay_pass(){
         global $islogin_user,$userrow;
         if($islogin_user != 1)exitjson(-1,'请先登录！');
         $pay_pass =  input("post")['pay_pass'];
         if(empty($pay_pass))exitjson(-1,'二级密码不能为空');
         if(empty($userrow['pay_pass']))exitjson(1,'您还没有设置二级密码 请先设置');
         $pwd = md5(md5($pay_pass));
         if($userrow['pay_pass'] == $pwd){
             $_SESSION['pay_pass']=$pwd;
             exitjson(200,'验证成功！');
         }
         exitjson(-1,'验证失败，二级密码错误！');
    }
    //手动回调
    public function Notify(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $trade_no = input("post")['trade_no'];
       
        $sql = "SELECT * FROM pay_order WHERE `trade_no` = :trade_no AND `pid` = :pid";
        $paramsSelect = [
            'trade_no' => $trade_no,
            'pid' => $user_pid
        ];
        $srow =  safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        $url=creat_callback($srow);
        $data=get_curl($url['notify']);
        createLog($user_pid,'人工补单回调',http_ip());  
        exitjson(200,'补单成功,并成功回调,接口返回数据：'.$data);
    }
    //支付宝免ck上传二维码
    public function Add_mckQr(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata            = input("post");
        $alipaymck_uid       = $postdata['alipaymck_uid'];
        $alipaymck_appid     = $postdata['alipaymck_appid'];
        $alipaypublicmck_key = $postdata['alipaypublicmck_key'];
        $appprivatemck_key   = $postdata['appprivatemck_key'];
        $beizhu              = $postdata['beizhu'];
        if( empty($alipaymck_uid) || empty($alipaymck_appid) || empty($alipaypublicmck_key) || empty($appprivatemck_key))exitjson(-1,'所有内容不可为空!');
        Examine::usernum();
        Examine::uservip('alipay');
        $sql = "SELECT * FROM pay_qrlist WHERE pid=:pid and alipayAppId=:alipayAppId limit 1";
        $paramsSelect = [
            'alipayAppId' => $alipaymck_appid,
            'pid' => $user_pid
        ];
        $srow =  safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if($srow)exitjson(-1,'添加失败,您之前已经添加过APPID地址 请勿重复添加！');
        $sql  = "SELECT * FROM pay_qrlist WHERE pid=:pid limit 1";
        $paramsSelect = [
            'pid' => $user_pid
        ];
       $srows =  safeSqlQuery($sql, $paramsSelect)['result'];
       foreach ($srows as $srow){
           $decodedCookie = base64_decode($srow['cookie']);
           $userId = getSubstr($decodedCookie, "CLUB_ALIPAY_COM=", ";");
           if ($userId == $alipaymck_uid) exitjson(-1,'添加失败，此账号已经存在 请换个账号在试或者删除此账号的免挂通道');
       }
       
       
        $sql = "INSERT INTO `pay_qrlist` (`pid`,`type`, `qr_url`,`cookie`,`money`,`beizhu`,`status`,`hook_type`,`addtime`,`alipayAppId`,`alipayUId`,`alipayPublicKey`,`appPrivateKey`) VALUES (:pid, :type, :qr_url, :cookie, :money, :beizhu, :status, :hook_type, :addtime, :alipayAppId, :alipayUId, :alipayPublicKey, :appPrivateKey)";
        $params = [
            'pid' => $user_pid,
            'type' => 'alipay',
            'qr_url' => '无',
            'cookie' => 'xfqymckxy',
            'money' => '0.00',
            'beizhu' => $beizhu,
            'status' => '1',
            'hook_type' => '0',
            'addtime' => $date,
            'alipayAppId' => $alipaymck_appid,
            'alipayUId' => $alipaymck_uid,
            'alipayPublicKey' => $alipaypublicmck_key,
            'appPrivateKey' => $appprivatemck_key
        ];
         if (safeSqlQuery($sql, $params, 'insert'))exitjson(200,'添加成功！');
         exitjson(-1,'添加失败！');
    }
    //支付宝当面付上传二维码
    public function Add_dmfQr(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata            = input("post");
        $alipaydmf_appid     = $postdata['alipaydmf_appid'];
        $alipaypublicdmf_key = $postdata['alipaypublicdmf_key'];
        $appprivatedmf_key   = $postdata['appprivatedmf_key'];
        $beizhu              = $postdata['beizhu'];
        
        if(empty($alipaydmf_appid) || empty($alipaypublicdmf_key) || empty($appprivatedmf_key))exitjson(-1,'所有内容不可为空！');
        Examine::usernum();
        $sql = "SELECT * FROM pay_qrlist WHERE pid=:pid and alipayAppId=:alipayAppId limit 1";
        $paramsSelect = [
            'alipayAppId' => $alipaydmf_appid,
            'pid' => $user_pid
        ];
        $srow =  safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if($srow)exitjson(-1,'添加失败,一个appid只能添加一次！');
        $sql = "INSERT INTO `pay_qrlist` (`pid`,`type`, `qr_url`,`cookie`,`money`,`beizhu`,`status`,`hook_type`,`addtime`,`alipayAppId`,`alipayPublicKey`,`appPrivateKey`) VALUES (:pid, :type, :qr_url, :cookie, :money, :beizhu, :status, :hook_type, :addtime, :alipayAppId, :alipayPublicKey, :appPrivateKey)";
        $params = [
            'pid' => $user_pid,
            'type' => 'alipay',
            'qr_url' => '无',
            'cookie' => 'xfqydmfxy',
            'money' => '0.00',
            'beizhu' => $beizhu,
            'status' => '1',
            'hook_type' => '0',
            'addtime' => $date,
            'alipayAppId' => $alipaydmf_appid,
            'alipayPublicKey' => $alipaypublicdmf_key,
            'appPrivateKey' => $appprivatedmf_key
        ];
        if (safeSqlQuery($sql, $params, 'insert'))exitjson(200,'添加成功！');
        exitjson(-1,'添加失败！');
    }
    //支付宝云端 上传二维码
    public function Add_Qr(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata  = input("post");
        $alipay    = $postdata['alipay'];
        $beizhu    = $postdata['beizhu'];
        if(empty($alipay))exitjson(-1,'请选择支付宝 协议');
         if ($alipay != '1' && $alipay != '2' && $alipay != '3')exitjson(-1,'协议参数不合法！');
        Examine::usernum();
        Examine::uservip('alipay');
        $sql = "INSERT INTO `pay_qrlist` (`pid`,`type`, `qr_url`,`cookie`,`money`,`beizhu`,`status`,`hook_type`,`addtime`,`xf_type`,`xf_stat`) VALUES (:pid,:type,:qr_url,:cookie,:money,:beizhu,:status,:hook_type,:date,:xf_type,:xf_stat)";
       $params = [
           'pid'=>$user_pid,
           'type'=>'alipay',
           'qr_url'=>'无',
           'cookie'=>'0',
           'money'=>'0.00',
           'beizhu'=>$beizhu,
           'status'=>'0',
           'hook_type'=>'0',
           'date'=>$date,
           'xf_type'=>$alipay,
           'xf_stat'=>'0'
           ];
     if (safeSqlQuery($sql, $params, 'insert'))exitjson(200,'添加成功！');
      exitjson(-1,'添加失败！');  
        
    }
    //QQ一类上传二维码 
    public function Add_QQQr(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
         $postdata  = input("post");
         $qqpay     = $postdata['qqpay'];
         $beizhu    = $postdata['beizhu'];
         if(empty($qqpay))exitjson(-1,'请选择QQ协议!');
         Examine::usernum();
         Examine::uservip('qqpay');
         $xf_stat = ($qqpay == '1') ? 0 : 1;
         if($qqpay != 1 && (empty($beizhu) || !is_numeric($beizhu))) exitjson(-1,'QQ不合法 或为空！');
         
         $sql = "INSERT INTO `pay_qrlist` (`pid`,`type`, `qr_url`,`cookie`,`money`,`beizhu`,`status`,`hook_type`,`addtime`,`xf_type`,`xf_stat`) VALUES (:pid,:type,:qr_url,:cookie,:money,:beizhu,:status,:hook_type,:date,:xf_type,:xf_stat)";
         $params = [
           'pid'=>$user_pid,
           'type'=>'qqpay',
           'qr_url'=>'无',
           'cookie'=>'0',
           'money'=>'0.00',
           'beizhu'=>$beizhu,
           'status'=>'0',
           'hook_type'=>'0',
           'date'=>$date,
           'xf_type'=>$qqpay,
           'xf_stat'=>$xf_stat
           ];
        if (safeSqlQuery($sql, $params, 'insert'))exitjson(200,'添加成功！');
       exitjson(-1,'添加失败！');     
    }
    //解码
    public function Add_Upload(){
        global $islogin_user,$httphost;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $rand=date("YmdHis").rand(11111,99999);
        $imgname = ROOT.'Core/assets/Upload/'.$rand.'.png';
        $Add = copy($_FILES['image_field']['tmp_name'],$imgname);
        $qrurl = $httphost.'/Core/assets/Upload/'.$rand.'.png';
        $QrApi = XFAPI_URL."/api/jiema.php?url=".$qrurl;
        $get_url=get_curl($QrApi);
        $json = json_decode($get_url, true);
        if($Add){
            if($json['code'] == '-2'){
                 unlink( $imgname); 
                 exitjson(-1,$json['code'],array("qrcode"=>"请删除此文字并前往草料二维码 进行解码粘贴并添加"));
            }else if($json['code'] == '1'){
                unlink( $imgname); 
                exitjson(200,'解码成功',array("qrcode"=>$json['qrurl']));
            }else{
                unlink( $imgname);
                exitjson(-1,$json['msg']);
            }
        }else{
            exitjson(-1,'上传二维码失败，请重新上传试试');
        }
    }
    //上传二维码
    public function Add_Upload1(){
        global $islogin_user,$httphost;
        // 文件类型验证
            $allowedTypes = ['image/png', 'image/jpeg', 'image/gif'];
            if (!in_array($_FILES['image_field']['type'], $allowedTypes)) {
                exitjson(-1, '只允许上传图片文件');
            }
            
            // 文件大小限制，假设限制为 5MB
            $maxFileSize = 5 * 1024 * 1024; // 5MB
            if ($_FILES['image_field']['size'] > $maxFileSize) {
                exitjson(-1, '文件大小超过限制');
            }
            
            // 文件名安全处理，使用安全的文件名
            $rand = date("YmdHis") . '_' . uniqid();
            $extension = pathinfo($_FILES['image_field']['name'], PATHINFO_EXTENSION);
            $name = ROOT . 'Core/assets/Upload/' . $rand . '.' . $extension;
            $qrurl = $httphost . '/Core/assets/Upload/' . $rand . '.' . $extension;
            
            // 文件内容检查，可选，根据需要进行内容检查
            
            // 存储路径安全性，确保目录存在且可写
            if (!file_exists(ROOT . 'Core/assets/Upload/') || !is_writable(ROOT . 'Core/assets/Upload/')) {
                exitjson(-1, '上传目录不存在或不可写');
            }
            
            // 执行文件上传
            $add = move_uploaded_file($_FILES['image_field']['tmp_name'], $name);
            if ($add) {
                exitjson(200, '上传成功！', array("qrcode" => $qrurl));
            } else {
                exitjson(-1, '上传失败');
            }
    }
    // 微信店员上传二维码
    public function Add_wx_QR(){
        global $islogin_user,$date,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata    =  input("post");
        $wxpay       =  $postdata['wxpay'];
        $qr_url      =  $postdata['qr_url'];
        $wx_user     =  $postdata['wx_name'];
        $beizhu      =  $postdata['beizhu'];
        if(empty($wxpay) || empty($qr_url) || empty($wx_user))exitjson(-1,'所有内容不可为空！');
        if($wxpay != 1)exitjson(-1,'挂机参数不合法');
        Examine::usernum();
        Examine::uservip('wxpay');
        $sql = "SELECT * FROM `pay_wechat_trumpet` WHERE  `wx_user`=:wx_user limit 1";
        $paramsSelect = [
            'wx_user' => $wx_user
        ];
        $xfsid = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$xfsid)exitjson(-1,'微信店员不存在 请核对后在试！');
         $wx_name=$xfsid['wx_name'];
        $sql = "INSERT INTO `pay_qrlist` (`pid`, `type`, `qr_url`, `cookie`, `money`, `beizhu`, `status`, `hook_type`, `addtime`, `xf_type`, `xf_stat`, `sid`, `wx_name`) 
        VALUES (:pid, :type, :qr_url, :cookie, :money, :beizhu, :status, :hook_type, :date, :xf_type, :xf_stat, :sid, :wx_name)";
        $params = [
            'pid' => $user_pid,
            'type' => 'wxpay',
            'qr_url' => $qr_url,
            'cookie' => '0',
            'money' => '0.00',
            'beizhu' => $beizhu,
            'status' => '0',
            'hook_type' => '0',
            'date' => $date,
            'xf_type' => $xfsid['mode'] == '1' ? 2 : 1,
            'xf_stat' => 0,
            'sid' => $xfsid['mode'] == '1' ? $xfsid['sid'] : null,
            'wx_name' => $wx_name
        ];
       if (safeSqlQuery($sql, $params, 'insert'))exitjson(200,'添加成功！');
       exitjson(-1,'添加失败！');     
    }
    // 微信Mac云端上传逻辑
    public function Add_wx_MacQR(){
        global $islogin_user,$date,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata    =  input("post");
        $qr_url      =  $postdata['qr_url'];
        $beizhu      =  $postdata['beizhu'];
        $mactype     =  $postdata['mactype'];
        $wxyunurl    =  $postdata['macwxyunurl']??NULL;
        if(empty($mactype))exitjson(-1,'请选择 Mac协议挂机方式');
        if (in_array($mactype, ['8', '9', '10'])) {
          if (empty($qr_url))  exitjson(-1, '收款码URL不可为空');
        }
        Examine::usernum();
        Examine::uservip('wxpay');
        $sql = "INSERT INTO `pay_qrlist` (`pid`,`type`, `cookie`,`money`,`qr_url`,`beizhu`,`wxyunurl`,`status`,`hook_type`,`xf_type`,`addtime`) VALUES (:pid,:type,:cookie,:money,:qr_url,:beizhu,:wxyunurl,:status,:hook_type,:xf_type,:date)";
        $qr_url = ($mactype == 1 || $mactype == 7) ? '无' : $qr_url;
        $params = [
            'pid'=>$user_pid,
            'type'=>'wxpay',
            'cookie'=>'0',
            'money'=>'0.00',
            'qr_url'=>$qr_url,
            'beizhu'=>$beizhu,
            'wxyunurl'=>$wxyunurl,
            'status'=>'0',
            'hook_type'=>'2',
            'xf_type'=>$mactype,
            'date'=>$date
        ];
        if (safeSqlQuery($sql, $params, 'insert'))exitjson(200,'添加成功！');
        exitjson(-1,'添加失败！');     
    }
    //微信Windows云端上传逻辑
    public function Add_wx_WindowsQR(){
        global $islogin_user,$date,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata    =  input("post");
        $qr_url      =  $postdata['qr_url'];
        $beizhu      =  $postdata['beizhu'];
        $wxyunurl    =  $postdata['uoswxyunurl']??NULL;
        $Windowstype     =  $postdata['Windowstype'];
        if(empty($Windowstype))exitjson(-1,'请选择 UOS协议挂机方式');
        if (in_array($Windowstype, ['4', '5', '6','3'])) {
          if (empty($qr_url))  exitjson(-1, '收款码URL不可为空');
        }
        Examine::usernum();
        Examine::uservip('wxpay');
        $sql = "INSERT INTO `pay_qrlist` (`pid`,`type`, `cookie`,`money`,`qr_url`,`beizhu`,`wxyunurl`,`status`,`hook_type`,`xf_type`,`addtime`) VALUES (:pid,:type,:cookie,:money,:qr_url,:beizhu,:wxyunurl,:status,:hook_type,:xf_type,:date)";
        $params = [
            'pid'=>$user_pid,
            'type'=>'wxpay',
            'cookie'=>'0',
            'money'=>'0.00',
            'qr_url'=>$qr_url,
            'beizhu'=>$beizhu,
            'wxyunurl'=>$wxyunurl,
            'status'=>'0',
            'hook_type'=>'2',
            'xf_type'=>$Windowstype,
            'date'=>$date
        ];
       if (safeSqlQuery($sql, $params, 'insert'))exitjson(200,'添加成功！');
        exitjson(-1,'添加失败！');    
    }
    
    public function Get_Qr(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
         $id   =  input("post")['id'];
         if(empty($id))exitjson(-1,'非法操作！');
         $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id
        ];
        $row = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$row)exitjson(-1,'非法操作');
        if (in_array($row['cookie'], ['xfqymckxy', 'xfqydmfxy'])) exitjson(-1,  '当面付和免CK不需要更新哦亲！');
        $sql = "SELECT * FROM `pay_wechat_trumpet` WHERE `status`='1' order by sort ASC";
        $rs  = safeSqlQuery($sql, []);
        if($rs['count']>0){
            foreach ($rs['result'] as $res){
                $data[] = $res;
            }
        }else{
            $data[]=array("wx_name"=>"暂无可添加微信","wx_user"=>"请联系站长");
        }
        $da = array(
            'id'=>$row['id'],
            'type'=>$row['type'],
            'beizhu'=>$row['beizhu'],
            'data'=>$data,
            'xfstat'=>$row['xf_stat']
            );
        exitjson(200,'获取成功！',$da);
    }
    public function Get_Login_QrCode(){
        global $islogin_user;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $type  = input("post")['type'];
        if(empty($type))exitjson(-1,'非法操作！');
        Examine::uservip($type);
        $result = XFCookie::Get_QrLogin($type);
        $sql = "update `pay_qrlist` set `qr_id`='{$result['id']}',`data_data`='0' WHERE `id`='{$qr_id}' limit 1";
        exitjson(200,'获取成功',$result);
    }
    public function Get_Login_Cookie(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata  = input("post");
        $type      = $postdata['type'];
        $id        = $postdata['id'];
        $qr_id     = $postdata['qr_id'];
        
        if(empty($type) || empty($id) || empty($qr_id))exitjson(-1,'非法操作！');
        Examine::uservip($type);
        $sql = "SELECT * FROM pay_qrlist WHERE `id`=:qr_id and `pid` = :pid limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'qr_id'=>$qr_id
        ];
        $row = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$row)exitjson(-2,'非法操作！');
        $result = XFCookie::Get_CooKie($type,$id);
        exitjson($result['code'],'success',$result);
        
    }
    public function Up_Qr(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata  = input("post");
        $id        = $postdata['id'];
        $cookie    = $postdata['cookie'];
        if(empty($id) || empty($cookie))exitjson(-1,'非法操作！');
        $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id
        ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if($is['type'] == 'alipay'){
    	     $userId = getSubstr($cookie, "CLUB_ALIPAY_COM=", ";");
    	     $sql = "SELECT * FROM pay_qrlist WHERE pid=:pid and cookie = 'xfqymckxy' ";
    	     $paramsSelect = [
                'pid' => $user_pid
            ];
    	     $srows = safeSqlQuery($sql,$paramsSelect)['result'];
    	     foreach ($srows as $srow){
    	         $alipayUId=$srow['alipayUId'];
    	         if ($userId == $alipayUId){
    	             exitjson(-1,'添加失败，此账号已经存在 请换个账号在试或者删除此账号的免CK通道');
    	         }
    	     }
    	}
    	if ($is['xf_type'] == '1') {
            $methodName = 'Get_pay_money';
        } else {
            $methodName = 'Get_pay_money' . $is['xf_type'];
        }
        
       if (method_exists('xfyzf\api\controller\Pay_Money_Api', $methodName)){
            $Pay_Money = Pay_Money_Api::$methodName($is['type'], $cookie);
        } else {
            exitjson(-1, '找不到对应的支付协议');
        }
    	if(!$Pay_Money['status'] && $is['type']!='wxpay'){
    	    $typeMapping = [
                'alipay' => '支付宝',
                'qqpay' => 'QQ',
            ];
          $type_name = $typeMapping[$is['type']] ?? '微信';
          exitjson(-1,"更新失败,请刷新页面重试,请换个! ".$type_name." 账号重试");
    	}
    	$sql  = "update `pay_qrlist` set `cookie`=:cookie,`money`=:money,`status`=:status,`addtime`=:addtime where id=:id";
    	$param = [
                'cookie' => $cookie,
                'money' =>$Pay_Money['money'],
                'status'=>1,
                'addtime'=>$date,
                'id'=>$id
        ];
        if (safeSqlQuery($sql, $param, 'update'))exitjson(200,'更新成功！');
        exitjson(-1,'更新失败！');
    }
    
    public function UP_DYQR(){
         global $islogin_user,$user_pid;
         if($islogin_user != 1)exitjson(-2,'请先登录！');
         $id = input("post")['qr_id'];
         if(empty($id))exitjson(-2,'非法操作！');
         $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id
        ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$is)exitjson(-2,'非法操作！');
        if(!$is['sid']){
            exitjson(1,'当前店员是普通店员 请加店员账号后 联系站长 强制绑定 没自动绑定的话');
        }
    }
    
    public function Get_QQPCQr(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $id = input("post")['id'];
        if(empty($id))exitjson(-1,'非法操作！');
        $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id
        ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$is)exitjson(-1,'非法操作！');
        Examine::uservip('qqpay');
        exitjson(200,'获取成功',array("id"=>$is['id'],"type"=>$is['type'],"beizhu"=>$is['beizhu']));
    }
    
    public function Get_QQPCLogin_QrCode(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata  = input("post");
        $id        = $postdata['id'];
        $type      = $postdata['type'];
        $beizhu    = $postdata['beizhu'];
        if(empty($id) || empty($beizhu))exitjson(-1,'非法操作！');
        $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id
        ];
        Examine::uservip($type);
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$is)exitjson(-1,'非法操作！');
        $code = -1;
        $msg = '未知错误';
        $result = QQ_Protocol::Get_QQPCQrLogin($type,$beizhu,$is['xf_type']);
        
        if($result){
            $code = 200; $msg = 'success';
        }
        exitjson($code,$code,$result);
    }
    public function GET_JIANCE(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata  = input("post");
        $type      = $postdata['type'];
        $qr_id     = $postdata['qr_id'];
        if(empty($type) || empty($qr_id))exitjson(-1,'非法操作');
        $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$qr_id
        ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$is)exitjson(-1,'非法操作');
        Examine::uservip($type);
        $result = QQ_Protocol::GET_JIANCE($type,$is['beizhu'],$is['xf_type']);
        // 定义状态码对应的消息
        $statusMessages = [
            '6' => '等待扫码',
            '1' => '登录成功',
            '-1' => '服务器错误'
        ];
        $message = $statusMessages[$result] ?? '等待下一轮循环';
        exitjson($result, $message);
    }
    public function Get_QQPCCOOKIE(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata  = input("post");
        $id        = $postdata['id'];
        $beizhu    = $postdata['beizhu'];
        if(empty($id) || empty($beizhu))exitjson(-1,'非法操作！');
        $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id
        ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$is)exitjson(-1,'非法操作');
        $result = QQ_Protocol::GET_QQPCCOOKIE($beizhu,$is['xf_type']);
        if($result['code']!='1')exitjson(-1,'服务器错误!');
        $cookie = $result['cookie'];
        $cookie1 = base64_decode($cookie);
        $userId = explode("qluin=",$cookie1)[1];
        $Pay_Money = Pay_Money_Api::Get_pay_money($is['type'], $cookie);
        if(!$Pay_Money['status'])exitjson(-1,"更新失败,请刷新页面重试,请换个! QQ 账号重试");
        $nextDay = date('Y-m-d H:i:s', strtotime('+12 hours')); 
        $sql = "update `pay_qrlist` set `cookie`=:cookie,`money`=:money,`status`=:status,`addtime`=:addtime , `chatime` =:chatime where id=:id";
        $param = [
                'cookie' => $cookie,
                'money' =>$Pay_Money['money'],
                'status'=>1,
                'addtime'=>$date,
                'chatime'=>$nextDay,
                'id'=>$id
        ];
        if (safeSqlQuery($sql, $param, 'update'))exitjson(200,'更新成功！');
        exitjson(-1,'更新失败！');
    }
    
    public function Get_Login_wxQrCode(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $id = input("post")['id'];
        if(empty($id))exitjson(-1,'非法操作！');
        $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id and `type`=:type and `hook_type`='2' limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id,
            'type'=>'wxpay'
        ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$is)exitjson(-1,'非法操作！');
        Examine::uservip('wxpay');
        $WXapi = createWxApiInstance($is);
       
        $result = $WXapi->wxlogin();
        
        $sebei = Examine::sebei($is['xf_type']);
        $code = '-1';
        $msg  = '获取失败！';
        if($result){
            $code = '200';
            $msg  = '获取成功';
            $result['jixin'] = $sebei;
        }
        exitjson($code,$msg,$result);
    }
    public  function Get_Login_wxCookie(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata  = input("post");
        $id        = $postdata['qr_id'];
        $guid      = $postdata['guid'];
        $uuid      = $postdata['uuid'];
        $type      = $postdata['type'];
        if(empty($id) || empty($uuid) || (empty($type) && $type !='wxpay'))exitjson(-1,'非法操作！');
        Examine::uservip('wxpay');
        $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id and `type`=:type and `hook_type`='2' limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id,
            'type'=>'wxpay'
        ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$is)exitjson(-1,'非法操作！');
        $WXapi = createWxApiInstance($is);
        $sebei = Examine::sebei($is['xf_type']);
        if($sebei == 'Mac'){
            $result = $WXapi->wxCheckLoginQrcode($guid,$uuid);
        }else{
            $result = $WXapi->wxCheckLoginQrcode($uuid);
            $result = json_decode($result,true);
            $guid   = $result['buid'];
        }
        exitjson($result['code'],$result['msg'],array("id"=>$id,"cookie"=>$guid));
    }
    public function Up_wxQr(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata  = input("post");
        $id        = $postdata['id'];
        $cookie    = $postdata['cookie'];
        if(empty($id) || empty($cookie))exitjson(-1,'非法操作!');
        $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id and `type`=:type and `hook_type`='2' limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'id'=>$id,
            'type'=>'wxpay'
        ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if(!$is)exitjson(-1,'非法操作！');
        $sql = "update `pay_qrlist` set `cookie`=:cookie,`status`=:status,`addtime`=:addtime where id=:id";
         $param = [
                'cookie' => $cookie,
                'status'=>1,
                'addtime'=>$date,
                'id'=>$id
        ];
        if (safeSqlQuery($sql, $param, 'update'))exitjson(200,'更新成功！');
        exitjson(-1,'更新失败！');
    }
    
    public function Del_Qr(){
         global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
         $id        = input("post")['id'];
         
         if(empty($id))exitjson(-1,'非法操作!');
          $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id  limit 1";
          $paramsSelect = [
                'pid' => $user_pid,
                'id'=>$id
          ];
         $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
         if(!$is)exitjson(-1,'非法操作！'); 
         $sql="DELETE FROM `pay_qrlist` WHERE `id`='{$id}' limit 1";
         if (executeSQLQuery($sql, 'delete')){
             createLog($user_pid,'删除二维码',http_ip());
             exitjson(200,'删除成功！');
         }
         exitjson(-1,'删除失败！');
         
    }
    public function edit_qr(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata  = input("post");
        $id        = $postdata['id'];
        $beizhu    = $postdata['beizhu']??'';
        $status    = $postdata['status']??'0';
        $nums      = $postdata['nums']??'0';
        $stat      = $postdata['stat']??'0';
        if(empty($id) || $stat === false || $status === false || $nums === false)exitjson(-1,'非法操作！');
         $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id  limit 1";
          $paramsSelect = [
                'pid' => $user_pid,
                'id'=>$id
          ];
         $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
         if(!$is)exitjson(-1,'非法操作！'); 
         $sql = "update `pay_qrlist` set `beizhu`=:beizhu ,`status`=:status ,`nums`=:nums , `stat`=:stat where id=:id";
         $param = [
                'beizhu' => $beizhu,
                'status'=>$status,
                'nums'=>$nums,
                'stat'=>$stat,
                'id'=>$id
        ];
        if (safeSqlQuery($sql, $param, 'update'))exitjson(200,'修改成功！');
        exitjson(-1,'修改失败！');
    }
    public function Add_usdt(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata     = input("post");
        $usdt_address = $postdata['usdt_address'];
        $beizhu       = $postdata['beizhu'];
        if(empty($usdt_address))exitjson(-1,'USDT收款地址不可为空！');
        Examine::usernum();
        Examine::uservip('usdtpay');
        $sql = "SELECT * FROM pay_qrlist WHERE `pid`=:pid and `qr_url`=:qr_url limit 1";
        $paramsSelect = [
            'pid' => $user_pid,
            'qr_url'=>$usdt_address
         ];
        $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if($is)exitjson(-1,'添加失败！您之前已经添加过此USDT收款地址');
        $sql = "INSERT INTO `pay_qrlist` (`pid`, `type`, `qr_url`, `cookie`, `money`, `beizhu`, `status`, `hook_type`, `addtime`) 
        VALUES (:pid, :type, :qr_url, :cookie, :money, :beizhu, :status, :hook_type, :addtime)";
        $param = [
                'pid' => $user_pid,
                'type'=>'usdtpay',
                'qr_url'=>$usdt_address,
                'cookie'=>$usdt_address,
                'money'=>'0.00',
                'beizhu'=>$beizhu,
                'status'=>1,
                'hook_type'=>0,
                'addtime'=>$date
        ];
        if (safeSqlQuery($sql, $param, 'insert'))exitjson(200,'添加成功！');
        exitjson(-1,'添加失败！');    
          
    }
    
    public function edit_usdt(){
         global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-2,'请先登录！');
        $postdata     = input("post");
        $usdt_address = $postdata['usdt_address'];
        $status       = $postdata['status'];
        $beizhu       = $postdata['beizhu'];
        $id           = $postdata['id'];
        if(empty($id))exitjson(-1,'非法操作！');
        if(empty($usdt_address))exitjson(-1,'USDT收款地址不可为空!');
        
         $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id  limit 1";
         $paramsSelect = [
                'pid' => $user_pid,
                'id'=>$id
          ];
       $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
       if(!$is)exitjson(-1,'非法操作');
       $sql = "update `pay_qrlist` set `beizhu`=:beizhu ,`status`=:status ,`qr_url`=:qr_url ,`cookie`=:cookie where id=:id";
       $param = [
                'beizhu' => $beizhu,
                'status'=>$status,
                'qr_url'=>$usdt_address,
                'cookie'=>$usdt_address,
                'id'=>$id
        ];
       if (safeSqlQuery($sql, $param, 'update'))exitjson(200,'修改成功！');
        exitjson(-1,'修改失败！');
    }
    public function Qrlist(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
         $id   = input("post")['id'];
         if(empty($id))exitjson(-1,'非法操作!');
         $sql = "SELECT * FROM `pay_qrlist` WHERE `pid`=:pid and `id`=:id  limit 1";
         $paramsSelect = [
                'pid' => $user_pid,
                'id'=>$id
          ];
       $row = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
       if(!$row)exitjson(-1,'非法操作');
       $today=date("Y-m-d").' 00:00:00';
       $today2=date("Y-m-d").' 23:59:59';
       $lastday=date("Y-m-d",strtotime("-1 day")).' 00:00:00';
       $lastday2=date("Y-m-d",strtotime("-1 day")).' 23:59:59';
       $qr_id=$row['id'];
        $sql = "SELECT 
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}') AS ddsl,
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}' AND status='1') AS zcgddsl,
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}' AND status!='1') AS zwwcddsl,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}') AS zpfddje,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}' AND status='1') AS zpfcgje,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}' AND status!='1') AS zpfwwcje,
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}' AND addtime>='$today' AND addtime<='$today2') AS jrzddsl,
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}' AND status='1' AND addtime>='$today' AND addtime<='$today2') AS jrzcgddsl,
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}' AND status!='1' AND addtime>='$today' AND addtime<='$today2') AS jrzwwcddsl,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}' AND addtime>='$today' AND addtime<='$today2') AS jrzpfddje,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}' AND status='1' AND endtime>='$today' AND endtime<='$today2') AS jrzpfcgje,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}' AND status!='1' AND addtime>='$today' AND addtime<='$today2') AS jrzpfwwcje,
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}' AND addtime>='$lastday' AND addtime<='$lastday2') AS zrzddsl,
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}' AND status='1' AND addtime>='$lastday' AND addtime<='$lastday2') AS zrzcgddsl,
                (SELECT COUNT(*) FROM pay_order WHERE qr_id='{$qr_id}' AND status!='1' AND addtime>='$lastday' AND addtime<='$lastday2') AS zrzwwcddsl,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}' AND addtime>='$lastday' AND addtime<='$lastday2') AS zrzpfddje,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}' AND status='1' AND endtime>='$lastday' AND endtime<='$lastday2') AS zrzpfcgje,
                (SELECT SUM(money) FROM pay_order WHERE qr_id='{$qr_id}' AND status!='1' AND addtime>='$lastday' AND addtime<='$lastday2') AS zrzpfwwcje";
    
        $result = executeSQLQuery($sql);
        
        // 从$result中获取相应的结果
        $ddsl = $result['ddsl']??'0';
        $zcgddsl = $result['zcgddsl']??'0';
        $zwwcddsl = $result['zwwcddsl']??'0';
        $zpfddje = $result['zpfddje']??'0';
        $zpfcgje = $result['zpfcgje']??'0';
        $zpfwwcje = $result['zpfwwcje']??'0';
        $jrzddsl = $result['jrzddsl']??'0';
        $jrzcgddsl = $result['jrzcgddsl']??'0';
        $jrzwwcddsl = $result['jrzwwcddsl']??'0';
        $jrzpfddje = $result['jrzpfddje']??'0';
        $jrzpfcgje = $result['jrzpfcgje']??'0';
        $jrzpfwwcje = $result['jrzpfwwcje']??'0';
        $zrzddsl = $result['zrzddsl']??'0';
        $zrzcgddsl = $result['zrzcgddsl']??'0';
        $zrzwwcddsl = $result['zrzwwcddsl']??'0';
        $zrzpfddje = $result['zrzpfddje']??'0';
        $zrzpfcgje = $result['zrzpfcgje']??'0';
        $zrzpfwwcje = $result['zrzpfwwcje']??'0';
      
      $row['ali_order'] = '总订单：'.$ddsl.'<br>'.'已完成：'.$zcgddsl.'<br>'.'未完成：'.$zwwcddsl.'<br>'.'成功率：'.(round((($zcgddsl?$zcgddsl:1) / ($ddsl?$ddsl:1)),2)*100).'%</td>
    	<td>'.'总金额：'.$zpfddje.'<br>'.'已完成：'.$zpfcgje.'<br>'.'未完成：'.$zpfwwcje;
    	
      $row['jr_order'] = '总订单：'.$jrzddsl.'<br>'.'已完成：'.$jrzcgddsl.'<br>'.'未完成：'.$jrzwwcddsl.'<br>'.'成功率：'.(round((($jrzcgddsl?$jrzcgddsl:1) / ($jrzddsl?$jrzddsl:1)),2)*100).'%</td>
    	<td>'.'总金额：'.$jrzpfddje.'<br>'.'已完成：'.$jrzpfcgje.'<br>'.'未完成：'.$jrzpfwwcje;
    	
      $row['zr_order'] = '总订单：'.$zrzddsl.'<br>'.'已完成：'.$zrzcgddsl.'<br>'.'未完成：'.$zrzwwcddsl.'<br>'.'成功率：'.(round((($zrzcgddsl?$zrzcgddsl:1) / ($zrzddsl?$zrzddsl:1)),2)*100).'%</td>
    	<td>'.'总金额：'.$zrzpfddje.'<br>'.'已完成：'.$zrzpfcgje.'<br>'.'未完成：'.$zrzpfwwcje;
      $row['type'] = '<img src="/Core/assets/icon/'.$row['type'].'.ico" width="16">'.pay_type($row['type']);
      exitjson(200,'success',$row);
    }
    public function Add_PC(){
        global $islogin_user,$user_pid,$date;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata  = input("post");
        $type      = $postdata['type'];
        $qr_url    = $postdata['qr_url'];
        $beizhu    = $postdata['beizhu'];
        if($type === false || empty($beizhu) )exitjson(-1,'所有内容不可为空！');
        if($type == '0') exitjson(-1,'支付宝和QQ 是自动添加的 用软件登录后 会自动添加');
        Examine::usernum();
        Examine::uservip('wxpay');
        if(empty($qr_url))exitjson(-1,'二维码url不可为空');
        $sql = "INSERT INTO `pay_qrlist` (`pid`,`type`, `cookie`,`money`,`qr_url`,`beizhu`,`uin`,`status`,`hook_type`,`xf_type`,`addtime`) VALUES (:pid,:type,:cookie,:money,:qr_url,:beizhu,:uin,:status,:hook_type,:xf_type,:addtime)";
        $param = [
                'pid' => $user_pid,
                'type'=>'wxpay',
                'cookie'=>'0',
                'money'=>'0.00',
                'qr_url'=>$qr_url,
                'beizhu'=>$beizhu,
                'uin'=>$beizhu,
                'status'=>0,
                'hook_type'=>1,
                'xf_type'=>$type,
                'addtime'=>$date
        ];
        
        if (safeSqlQuery($sql, $param, 'insert'))exitjson(200,'添加成功！');
        exitjson(-1,'添加失败！');    
    }
    public function Qr_Code(){
        global $islogin_user,$user_pid,$date,$userrow,$httphost,$conf;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $sub = $conf['sitename'].' - 修改资料验证码';
        $code = rand(1111111,9999999);
        $email = $userrow['email'];
        // $surl = $httphost.'/User/ban?token='.$token;
        
        $data=[
            'user'=>$userrow['user'],
            'paragraphs' => [
                ['label' => '尊敬的用户 PID:', 'value' => $user_pid.'您好！'],
                ['label' => '您的修改资料验证码是：', 'value' => $code],
                ['label' => '如非本人操作请尽快修改密码 避免被盗!','value'=>''],
                // ['label' => '紧急冻结：','value'=>$surl],
                ['label' => '有问题请联系站长QQ:','value'=>$conf['qq']]
                ]
        ];
        
        $sql = "insert into `pay_regcode` (`type`,`code`,`to`,`time`,`ip`,`status`) values (:type,:code,:email,:time,:ip,:status)";
        $param = [
                'type'=>'3',
                'code'=>$code,
                'email'=>$email,
                'time'=>time(),
                'ip'=>http_ip(),
                'status'=>0
        ];
         if (safeSqlQuery($sql, $param, 'insert')){
             $result = send_mail($email, $sub, Mailbox_sending_template($data,'修改资料验证码'));
             if(!$result)exitjson(-1,'验证码写入成功 但发送失败！');
             exitjson(200,'验证码发送成功！');
         }
         exitjson(-1,'验证码写入失败！');
    }
    public function Set(){
        global $islogin_user,$user_pid,$userrow;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata  = input("post");
        $pass      = $postdata['pass'];
        $qq        = $postdata['qq'];
        $pay_pass  = $postdata['pay_pass'];
        $code      = $postdata['code'];
        if(empty($pass) || empty($qq) || empty($pay_pass) || empty($code))exitjson(-1,'所有内容不可为空！');
        $sql = "select * from `pay_regcode` where `type`='3' and `code`='{$code}' and `to`='{$userrow['email']}' order by id desc limit 1";
        $row = executeSQLQuery($sql);
        if(!$row)exitjson(-1,'验证码不正确');
        if ($row['time'] < time() - 3600 || $row['status'] > 0)exitjson(-1,'验证码已失效，请重新获取');
        if(strlen($pass) < 6 || strlen($pay_pass) < 6)exitjson(500, "密码长度不能少于6位");
        if(ctype_digit($pass))exitjson(500, "密码过于简单，请使用包含字母、数字和特殊字符的更复杂密码");
        $pass = md5(md5($pass));
        $pay_pass =md5(md5($pay_pass));
        $sql = "update `pay_user` set `pass`=:pass,`pay_pass`=:pay_pass,`qq`=:qq where pid=:pid";
        $param = [
                'pass'=>$pass,
                'pay_pass'=>$pay_pass,
                'qq'=>$qq,
                'pid'=>$user_pid
        ];
        if (safeSqlQuery($sql, $param, 'update')){
            createLog($user_pid,'修改资料',http_ip());
            exitjson(200,'修改成功！');
        }
        exitjson(-1,'修改失败！');
    }
    public function Pay_Buy(){
        global $islogin_user,$user_pid,$userrow,$conf;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $type  = input("post")['type'];
        if(empty($type))exitjson(-1,'请选择要购买的会员套餐');
        $name = '购买会员';
        $trade_no = date("YmdHis").rand(11111,99999);	
        $money = $conf[$type.'_free_vip_money'];
        $name = array(
            'wxpay'=>'微信',
            'qqpay'=>'QQ',
            'alipay'=>'支付宝'
            );
        $type_name = $name[$type];
        
        $data = array(
            'name'=>'购买会员',
            'trade_no'=>$trade_no,
            'money'=>$money,
            'type_name'=>$type_name
            );
         if(insertIntoInsideOrder($trade_no,$userrow['pid'],$money, $type)){
             exitjson(200,'创建成功！',$data);
         }
         exitjson(-1,'订单创建失败！');
    }
    public function Pack_Buy(){
        global $islogin_user,$user_pid,$userrow,$conf;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $id = input("post")['id']??'';
        if(empty($id))exitjson(-1,'请选择要购买的套餐');
        $sql    = "SELECT * FROM pay_package WHERE `status`='1' AND `id`='{$id}'";
        $row = executeSQLQuery($sql);
        if(!$row)exitjson(-1,'非法操作！');
        $name = '购买套餐';
        $trade_no = date("YmdHis").rand(11111,99999);	
        $data = array(
            'name'=>$name,
            'trade_no'=>$trade_no,
            'money'=>$row['price'],
        );
       if(insertIntoInsideOrder($trade_no,$user_pid,$row['price'], $row['id'])){
             exitjson(200,'创建成功！',$data);
       }
       exitjson(-1,'订单创建失败！');
    }
    public function Change_pay_Template(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $pay_template = input("post")['pay_template'];
        if(empty($pay_template))exitjson(-1,'请选择要切换的模板');
        $sql = "update `pay_user` set `pay_template` =:pay_template where `pid`=:pid";
        $param = [
                'pay_template'=>$pay_template,
                'pid'=>$user_pid
        ];
        if (safeSqlQuery($sql, $param, 'update')){
             createLog($user_pid,'修改支付模板成功',http_ip());
            exitjson(200,'更换支付模板成功！');
        }
        exitjson(-1,'更换支付模板失败！');
    }
    public function pay_set(){
        global $islogin_user,$user_pid;
        if($islogin_user != 1)exitjson(-1,'请先登录！');
        $postdata = input("post");
        $INPUTFREE = $postdata['INPUTFREE'];
        $wxpb_llq  = $postdata['wxpb_llq'];
        $user_vips = $postdata['user_vips'];
        $outtime   = $postdata['outtime'];
        if($INPUTFREE === false || $wxpb_llq === false || $user_vips === false || $outtime === false)exitjson(-1,'所有内容不可为空！');
        $sql = "update `pay_user` set `INPUTFREE`=:INPUTFREE,`user_vips`=:user_vips ,`wxpb_llq`=:wxpb_llq,`outtime`=:outtime where pid=:pid";
        $param = [
                'INPUTFREE'=>$INPUTFREE,
                'user_vips'=>$user_pid,
                'wxpb_llq'=>$wxpb_llq,
                'pid'=>$user_pid,
                'outtime'=>$outtime
        ];
       if (safeSqlQuery($sql, $param, 'update')){
            createLog($user_pid,'修改商户支付配置信息',http_ip());
            exitjson(200,'修改成功');
       }
       exitjson(-1,'修改失败！');
    }
    public function Get_Work(){
        global $userrow,$islogin_user,$conf,$date,$httphost; 
        if($islogin_user != 1)exitjson(-1,"请先登录");
        $postdata = input("post");
        $types    = $postdata['types'];
        $biaoti   = $postdata['biaoti'];
        $text     = $postdata['text'];
        $qq       = $postdata['qq'];
        if(empty($types) || empty($biaoti) || empty($text) || empty($qq))exitjson(-1,'所有内容不可为空');
        if($conf['work_zt'] == '0')exitjson(-1,'管理员未开启工单!');
        if(isset($_SESSION['work_submit']) && $_SESSION['work_submit']>time()-2400)exitjson(-1,'请勿频繁提交工单！');
        $num = rand(100000000,999999999);
        $sql = "INSERT INTO `pay_work` (`uid`, `num`, `types`, `biaoti`, `text`, `qq`, `edata`, `active`) VALUES (:uid, :num, :types, :biaoti, :text, :qq, :edata, :active)";
        $param = [
                'uid'=>$userrow['pid'],
                'num'=>$num,
                'types'=>$types,
                'biaoti'=>$biaoti,
                'text'=>$text,
                'qq'=>$qq,
                'edata'=>$date,
                'active'=>0
        ];
         if (safeSqlQuery($sql, $param, 'insert')){
              $_SESSION['work_submit']=time();
              $email = $conf['mail_recv'];
              $sub = $conf['sitename'].' - 您有新的工单要处理';
              $data = [
                'user' => '管理员',
                'paragraphs' => [
                    ['label' => '新的工单等您来处理！'],
                    ['label' => '尊敬的管理员您的网站【'.$conf['sitename'].'】收到一个工单'],
                    ['label' => '工单编号为：', 'value' => $num,'fontSize'=>'12'],
                    ['label' => '工单类型为：', 'value' => $types,'fontSize'=>'12'],
                    ['label' => '工单标题为：', 'value' => $biaoti,'fontSize'=>'12'],
                    ['label' => '请尽快登录后台处理工单', 'fontSize'=>'12'],
                ]
            ];
            $msg = Mailbox_sending_template($data, '新工单消息'); 
            $result = send_mail($email, $sub, $msg);
            exitjson(200,"发起工单成功！");
         }
         exitjson(-1,'发起失败！'); 
    }
    public function edit_codename(){
         global $userrow,$islogin_user; 
         if($islogin_user != 1)exitjson(-1,"请先登录");
         $codename = input("post")['codename'];
         if(empty($codename))exitjson(-1,'名称 不可为空！');
         $sql = "update `pay_user` set `codename`=:codename  where `pid`=:pid";
         $param = [
                'codename'=>$codename,
                'pid'=>$userrow['pid']
        ];
        if (safeSqlQuery($sql, $param, 'update')){
            exitjson(200,'修改成功');
        }
       exitjson(-1,'修改失败！');
    }
    public function _zh_code(){
        global $conf,$islogin_user;
        if($islogin_user == 1)exitjson(-1,"您已登录");
        if($conf['zh_open'] != '1')exitjson(-1,'管理员未开启找回功能');
        $postdata = input("post");
        $username = $postdata['username'];
        $qq       = $postdata['qq'];
        if(empty($username) || empty($qq))exitjson(-1,'用户名和QQ不可为空！');
        $sql = "SELECT * FROM `pay_user` WHERE `qq` = '{$qq}' LIMIT 1";
        $row=executeSQLQuery($sql); 
        if(!$row)exitjson(-1,"该QQ未注册此平台，请更换后在试");
        if($row['user']!=$username)exitjson(-1,"用户名错误");
        if(isset($_SESSION['send_mail']) && $_SESSION['send_mail']>time()-10)exitjson(-1,"请勿频繁发送验证码");
        $email = $row['email'];
        $sql="SELECT * FROM pay_regcode WHERE `to`='{$to}' order by id desc limit 1";
        $row=executeSQLQuery($sql);
        if($row['time']>time()-60)exitjson(-1,"两次发送短信之间需要相隔60秒！");
        $sql  = "select count(*) as count from pay_regcode where `to`='$to' and time>'".(time()-3600*24)."'";
        if(executeSQLQuery($sql)['count']>6)exitjson(-1,"发送次数过多，请更换收信方式！");
        $sql = "select count(*) as count from pay_regcode where ip='".http_ip()."' and time>'".(time()-3600*24)."'";
        if(executeSQLQuery($sql)['count']>10)exitjson(-1,"你今天发送次数过多，已被禁止找回");
        $code = rand(111111,999999);
        $msg = '尊敬的用户您好 您的验证码是：'.$code.'，本验证码是找回密码的验证码 如非本人操作请及时处理！';
        $result = send_mail($email, $sub, $msg);	
        if($result==true){
            $sql = "insert into `pay_regcode` (`type`,`code`,`to`,`time`,`ip`,`status`) values ('0','".$code."','".$email."','".time()."','".http_ip()."','0')";
            if(executeSQLQuery($sql,'insert')){
                $_SESSION['send_mail']=time();
                exitjson(200,'验证码发送成功！请注意查收');
            }else{
                exitjson(-1,'验证码存储失败！');
            }
        }
        exitjson(-1,'验证码发送失败！');
    }
    public function _zh_pwd(){
        global $conf,$islogin_user;
        if($islogin_user == 1)exitjson(-1,"您已登录");
        if($conf['zh_open'] != '1')exitjson(-1,'管理员未开启找回功能');
        $postdata  = input("post");
        $username  = $postdata['username'];
        $password  = $postdata['password'];
        $newpass   = $postdata['newpass'];
        $qq        = $postdata['qq'];
        $code      = $postdata['code'];
        if(empty($username) || empty($password) || empty($newpass) || empty($qq) || empty($code))exitjson(-1,'所有内容不可为空');
        if($password!=$newpass)exitjson(-1,'两次输入的密码不一致 请核对后在试');
        $sql = "SELECT * FROM `pay_user` WHERE `user` = '{$username}' LIMIT 1";
        $row=executeSQLQuery($sql); 
        if(!$row)exitjson(-1,'用户名错误！');
        if (strlen($password) < 6)exitjson(500, "密码长度不能少于6位");
        if (ctype_digit($password))exitjson(500, "密码过于简单，请使用包含字母、数字和特殊字符的更复杂密码");
        if (!is_numeric($code) && strlen($code) != 6)exitjson(500,"验证码格式不正确");
        if($row['pwd']== md5(md5($password)))exitjson(-1,"新密码不能和旧密码 一致");
        $to = $row['email'];
        $sql="select * from `pay_regcode` where `type`='0' and `code`='{$code}' and `to`='{$to}' order by id desc limit 1";
        $res=executeSQLQuery($sql); 
        if(!$res)exitjson(-1,"您输入的验证码有误请核对后在试！");
        if($res['time']<time()-300 || $res['status']==1)exitjson(-1,"验证码已失效，请重新获取");
        $pass=md5(md5($password));
        $sql = "update `pay_user` set `pass` ='$pass' where user='{$username}'";
        if(executeSQLQuery($sql,'update')){
            $sql1="update `pay_regcode` set `status` ='1' where `id`='{$res['id']}'";
            executeSQLQuery($sql1, 'update');
            createLog($row['pid'],'找回密码成功！',http_ip());
            exitjson(200,"恭喜您成功找回密码!");
        }else{
            exitjson(-1,'找回失败！');
        }
    }
}




?>